package com.arvin.faceDetect.utils

import android.util.Log
import kotlin.math.abs
import kotlin.math.sqrt

object FeatureQualityAnalyzer {
    private const val TAG = "FeatureQualityAnalyzer"

    // 特征向量质量阈值
    private const val MIN_FEATURE_NORM = 0.8f  // 特征向量范数最小值
    private const val MAX_FEATURE_NORM = 1.2f  // 特征向量范数最大值
    private const val MIN_FEATURE_ENTROPY = 4.0f  // 特征向量熵最小值
    private const val MAX_FEATURE_SIMILARITY = 0.95f  // 特征向量相似度最大值

    /**
     * 分析特征向量质量
     * @param features 特征向量
     * @return 特征质量评估结果
     */
    fun analyzeFeatureQuality(features: FloatArray): FeatureQualityResult {
        // 1. 计算特征向量范数
        val norm = calculateNorm(features)

        // 2. 计算特征向量熵
        val entropy = calculateEntropy(features)

        // 3. 计算特征向量分布
        val distribution = analyzeDistribution(features)

        // 4. 评估特征质量
        val isNormValid = norm in MIN_FEATURE_NORM..MAX_FEATURE_NORM
        val isEntropyValid = entropy >= MIN_FEATURE_ENTROPY
        val isDistributionValid = distribution.isValid

        val quality = when {
            !isNormValid -> FeatureQuality.INVALID_NORM
            !isEntropyValid -> FeatureQuality.LOW_ENTROPY
            !isDistributionValid -> FeatureQuality.POOR_DISTRIBUTION
            else -> FeatureQuality.GOOD
        }

        Log.d(
            TAG, """
            特征质量分析结果:
            范数: $norm (${if (isNormValid) "有效" else "无效"})
            熵: $entropy (${if (isEntropyValid) "有效" else "无效"})
            分布: ${distribution.description}
            质量等级: $quality
        """.trimIndent()
        )

        return FeatureQualityResult(
            quality = quality,
            norm = norm,
            entropy = entropy,
            distribution = distribution
        )
    }

    /**
     * 计算特征向量范数
     */
    private fun calculateNorm(features: FloatArray): Float {
        var sum = 0f
        for (value in features) {
            sum += value * value
        }
        return sqrt(sum)
    }

    /**
     * 计算特征向量熵
     */
    private fun calculateEntropy(features: FloatArray): Float {
        // 将特征值归一化到[0,1]区间
        val normalized = normalizeFeatures(features)

        // 计算熵
        var entropy = 0f
        for (value in normalized) {
            if (value > 0) {
                entropy -= value * kotlin.math.ln(value)
            }
        }
        return entropy
    }

    /**
     * 分析特征向量分布
     */
    private fun analyzeDistribution(features: FloatArray): FeatureDistribution {
        // 计算均值和标准差
        var mean = 0f
        for (value in features) {
            mean += value
        }
        mean /= features.size

        var variance = 0f
        for (value in features) {
            variance += (value - mean) * (value - mean)
        }
        variance /= features.size
        val stdDev = sqrt(variance)

        // 计算偏度和峰度
        var skewness = 0f
        var kurtosis = 0f
        for (value in features) {
            val z = (value - mean) / stdDev
            skewness += z * z * z
            kurtosis += z * z * z * z
        }
        skewness /= features.size
        kurtosis /= features.size

        // 评估分布质量
        val isNormal = abs(skewness) < 1.0f && abs(kurtosis - 3.0f) < 2.0f
        val isUniform = stdDev < 0.2f

        return FeatureDistribution(
            mean = mean,
            stdDev = stdDev,
            skewness = skewness,
            kurtosis = kurtosis,
            isValid = isNormal || isUniform,
            description = when {
                isNormal -> "近似正态分布"
                isUniform -> "近似均匀分布"
                else -> "异常分布"
            }
        )
    }

    /**
     * 归一化特征向量
     */
    private fun normalizeFeatures(features: FloatArray): FloatArray {
        val min = features.minOrNull() ?: 0f
        val max = features.maxOrNull() ?: 1f
        val range = max - min

        return if (range > 0) {
            FloatArray(features.size) { i ->
                (features[i] - min) / range
            }
        } else {
            features
        }
    }

    /**
     * 特征质量等级
     */
    enum class FeatureQuality {
        GOOD,           // 特征质量好
        INVALID_NORM,   // 特征范数异常
        LOW_ENTROPY,    // 特征熵值低
        POOR_DISTRIBUTION  // 特征分布差
    }

    /**
     * 特征分布信息
     */
    data class FeatureDistribution(
        val mean: Float,
        val stdDev: Float,
        val skewness: Float,
        val kurtosis: Float,
        val isValid: Boolean,
        val description: String
    )

    /**
     * 特征质量评估结果
     */
    data class FeatureQualityResult(
        val quality: FeatureQuality,
        val norm: Float,
        val entropy: Float,
        val distribution: FeatureDistribution
    )
} 